package cn.qayy.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.CollectionConstant;
import cn.qayy.constants.Constant;
import cn.qayy.dto.CargoInvoiceApplyDTO;
import cn.qayy.dto.CargoInvoiceApplyDownMB;
import cn.qayy.dto.CargoInvoiceApplyDownXJMB;
import cn.qayy.dto.Msg;
import cn.qayy.po.CargoInvoiceApply;
import cn.qayy.po.Plan;
import cn.qayy.service.IBasisService;
import cn.qayy.service.ICargoService;
import cn.qayy.service.IPlanService;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.ExcelUtils;
import cn.qayy.utils.StringUtil;

/**
 * 货票申请 controller
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/cargo/")
public class CargoInvoiceApplyController {
	// 注入service
	@Resource(name = "cargoInvoiceApplyImpl")
	private ICargoService cargoService = null;

	@Resource(name = "planServiceImpl")
	private IPlanService planService = null;
	
	@Resource(name = "basisServiceImpl")
	private IBasisService basisService = null;
	
	List<String> multiselectCondi = new ArrayList<String>(); // 可多选的条件

	/**
	 * 根据查询条件，查询结果列表
	 * @param dto
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectForList")
	public Object selectForList(CargoInvoiceApplyDTO dto,HttpServletRequest request) {
		Msg msg = null;
		try {
			PageInfo<CargoInvoiceApply> pageInfo = cargoService.selectForList(dto);
			msg = new Msg(Constant.SUCESSFUL_CODE, pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	/**
	 * 根据id查询
	 * @param dto
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectByID")
	public Object selectByID(Long id,HttpServletRequest request) {
		Msg msg = null;
		try {
			CargoInvoiceApply cargo = cargoService.selectByID(id);
			msg = new Msg(Constant.SUCESSFUL_CODE,cargo);
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	/**
	 * 根据id删除
	 * @param dto
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "deleteByID")
	public Object deleteByID(Long id,HttpServletRequest request) {
		Msg msg = null;
		try {
			CargoInvoiceApply cargo = cargoService.selectByID(id);
			if(cargo != null) {
				int i = cargoService.deleteByPrimaryKey(cargo.getId());
				System.out.println("i="+i);
				if(i > 0) {
					msg = new Msg(Constant.SUCESSFUL_CODE,"删除成功");
				} else {
					msg = new Msg(Constant.FAIL_CODE,"删除失败");
				}
			} else {
				msg = new Msg(Constant.FAIL_CODE,"删除失败，找不到删除的对象");
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	/***
	 * 为了完善form表单数据而查询
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectForFill")
	public Object selectForFill(String kaipiaodanwei,String client,String product,String pack) {
		Msg msg = null;
		try {
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("kaipiaodanwei", kaipiaodanwei);
			params.put("client", client);
			params.put("product", product);
			params.put("pack",pack);
			CargoInvoiceApply cargoInvoiceApply = cargoService.selectLastOneByMap(params);
			if(cargoInvoiceApply == null) {
				msg = new Msg(Constant.FAIL_CODE,"没有找到相关记录，请自行手动完善");
			} else {
				msg = new Msg(Constant.SUCESSFUL_CODE,cargoInvoiceApply);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	/**
	 * 新增、更新
	 * @param cargo
	 * @param flag
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "saveOrUpdate")
	public Object saveOrUpdate(CargoInvoiceApply cargo,String flag, HttpServletRequest request) {
		Msg msg = null;
		try {
//			String kaipiaodanwei = cargo.getKaipiaodanwei();
//			/***
//			 * 获取项目上下文的共享数据
//			 */
//			ServletContext servletContext = ServletContextUtils.getServletContext();
//			HashSet<String> cNames = ((HashSet<String>)servletContext.getAttribute("cNames"));
//			if(!cNames.contains(kaipiaodanwei)) {
//				msg = new Msg(Constant.CHECK_CODE, "开票单位尚未在【注册库】中注册，请先注册");
//				return msg;
//			}
			cargo.setCrateTime(new Date());
			cargo.setUpdateTime(new Date());
			//获取到当前登录用户的归属地，判断是否需要获取片区
			String hobby = request.getSession().getAttribute("hobby").toString();
			if(hobby.equals("深圳发货岗")) {
				//根据填写的经理获取片区
				String space = basisService.selectSpaceByMgr(cargo.getMgr());
				if(StringUtil.isNotBlank(space)) {
					cargo.setSpace(space);
				}
			}
			cargo.setDataer(request.getSession().getAttribute("username")+"");
			Map<String, Object> params = new HashMap<String,Object>();
			params.put("commercial1", cargo.getKaipiaodanwei());
			List<Plan> list = planService.selectByMap(params);
			if(list != null && list.size()>0) {
				cargo.setHasPlans("有");
			}
			if (flag.equals("N")) { // N:新增
				cargoService.insert(cargo);
			} else if (flag.equals("E")) {// E:修改
				if(StringUtil.isNotBlank(cargo.getDeliveryDanhao()) 
						&& StringUtil.isNotBlank(cargo.getDeliveryWuliu())
						&& StringUtil.isNotBlank(cargo.getKaipiaoNo())
						&& StringUtil.isNotBlank(cargo.getTicketNumber())
						&& StringUtil.isNotBlank(cargo.getKaipiaoTime()+"")) {
					cargo.setStatus("新疆已处理");
				}
				cargoService.update(cargo);
			}
			msg = new Msg(Constant.SUCESSFUL_CODE, Constant.SUCESSFUL_MSG);
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}

	/***
	 * 页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<CargoInvoiceApplyDownMB> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(CargoInvoiceApplyDownMB.class);
			List<CargoInvoiceApplyDownXJMB> loadDataListXJ = new ArrayList<CargoInvoiceApplyDownXJMB>();
			String pack = "S";
			for (CargoInvoiceApplyDownMB mb : loadDataList) {
				if("A".equals(mb.getProduct())) {
					mb.setProduct("安胃疡胶囊");
				}
				if("Y".equals(mb.getProduct())) {
					mb.setProduct("复方银翘氨敏胶囊");
				}
				if("Z".equals(mb.getProduct())) {
					mb.setProduct("复方甘草浙贝氯化铵片");
					pack = "片";
				}
				if("B".equals(mb.getProduct())) {
					mb.setProduct("板蓝根颗粒");
					pack = "包";
				}
				CargoInvoiceApplyDownXJMB xjmb = new CargoInvoiceApplyDownXJMB();
				xjmb.setChukudanhao(mb.getChukudanhao());
				xjmb.setClient(mb.getClient());
				xjmb.setCount(mb.getCount());
				xjmb.setCrateTime(mb.getCrateTime());
				xjmb.setDataer(mb.getDataer());
				xjmb.setDelivery_apply_time(mb.getDelivery_apply_time());
				xjmb.setDelivery_danhao(mb.getDelivery_danhao());
				xjmb.setDelivery_demo(mb.getDelivery_demo());
				xjmb.setDelivery_wuliu(mb.getDelivery_wuliu());
				xjmb.setGoods_addr(mb.getGoods_addr());
				xjmb.setGoods_man(mb.getGoods_man());
				xjmb.setGoods_phone(mb.getGoods_phone());
				xjmb.setHas_huopiaotongxing(mb.getHas_huopiaotongxing());
				xjmb.setHas_plans(mb.getHas_plans());
				xjmb.setKaipiao_apply_time(mb.getKaipiao_apply_time());
				xjmb.setKaipiao_demo(mb.getKaipiao_demo());
				xjmb.setKaipiao_no(mb.getKaipiao_no());
				xjmb.setKaipiao_time(mb.getKaipiao_time());
				xjmb.setKaipiaodanwei(mb.getKaipiaodanwei());
				xjmb.setKaipiaojia(mb.getKaipiaojia());
				xjmb.setMgr(mb.getMgr());
				xjmb.setMoney(mb.getMoney());
				xjmb.setPay_note(mb.getPay_note());
				if("-1".equals(mb.getPcount())) {
					xjmb.setPcount("散货");
				} else {
					xjmb.setPcount(mb.getPcount());
				}
				
				xjmb.setPici(mb.getPici());
				
				xjmb.setProduct_pack(mb.getProduct()+mb.getPack()+pack);
				xjmb.setPzmoney(mb.getPzmoney());
				xjmb.setSmall_pici(mb.getSmall_pici());
				xjmb.setSpace(mb.getSpace());
				xjmb.setStatus(mb.getStatus());
				xjmb.setTiaoxiang(mb.getTiaoxiang());
				xjmb.setTicket_addr(mb.getTicket_addr());
				xjmb.setTicket_iphone(mb.getTicket_iphone());
				xjmb.setTicket_man(mb.getTicket_man());
				xjmb.setTicket_number(mb.getTicket_number());
				xjmb.setUpdateTime(mb.getUpdateTime());
				loadDataListXJ.add(xjmb);
			}
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("货票申请",StringUtil.listToStrArray(CollectionConstant.cargoInvoiceApply_mb),loadDataListXJ);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	/***
	 * 检验重复项、联想一下
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "checkRssociation")
	public Object checkRssociation(String chukudanhao,String client,String kaipiaodanwei,String type) {
		Msg msg = null;
		try {
			Map<String,Object> params = new HashMap<String,Object>();
			if("2".equals(type)) {
				params.put("chukudanhao", chukudanhao);
			} else if("4".equals(type)) {
				params.put("client", client);
			} else if("3".equals(type)) {
				params.put("kaipiaodanwei", kaipiaodanwei);
			}
			
			List<CargoInvoiceApply> cargoList = cargoService.checkRssociation(params);
			if(type.equals("1")) { //1:重复项
				if(cargoList.size()>=1) {//存在重复项
					msg = new Msg(Constant.FAIL_CODE,"存在重复项，请重新输入！");
				}else {	//检验通过
					msg = new Msg(Constant.SUCESSFUL_CODE,"检验通过！");
				}
			}else { //2:联想
				if(cargoList.size() == 0) {
					msg = new Msg(Constant.FAIL_CODE,"没有找到相关记录，请自行手动完善!");
				} else {
					msg = new Msg(Constant.SUCESSFUL_CODE,cargoList.get(0));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/***
	 * 展示UI页面
	 * @return
	 */
	@RequestMapping(value="ui.do")
	public ModelAndView ui(HttpServletRequest req) {
		ServletContext context = req.getSession().getServletContext();
		
		ModelAndView model = new ModelAndView();
		model.setViewName("cargo_search");
		//获取注册库中的开票单位
		model.addObject("kaipiaodanwei",JSONObject.toJSONString(context.getAttribute("commercial1List"))); //json格式
		//获取品种
		model.addObject("products", CollectionConstant.products);
		//获取包装
		model.addObject("packs", CollectionConstant.packs);
		//获取条线
		model.addObject("txs", CollectionConstant.txs);
		//获取流向表的客户
		model.addObject("clientList", JSONObject.toJSONString(context.getAttribute("clientList")));
		
		//获取流向表的片区
		model.addObject("spaces", JSONObject.toJSONString(context.getAttribute("spaceList")));
		
		//获取流向表的经理
		model.addObject("mgrs", JSONObject.toJSONString(context.getAttribute("mgrList")));
		
		return model;
	}
	
}
